// useImageColor.ts
import { useEffect, useState } from 'react';
import ColorThief from 'colorthief';

/**
 * 从图片提取主色调
 * @param imageUrl 图片地址
 * @returns 主色调（hex 格式）
 */
export function useImageColor(imageUrl: string) {
  const [mainColor, setMainColor] = useState<string | null>(null);

  useEffect(() => {
    if (!imageUrl) return;

    const img = new Image();
    img.crossOrigin = 'Anonymous'; // 处理跨域
    img.src = imageUrl;

    img.onload = () => {
      try {
        const colorThief = new ColorThief();
        const result = colorThief.getColor(img); // [r, g, b]
        const hex = `#${result.map(x => x.toString(16).padStart(2, '0')).join('')}`;
        setMainColor(hex);
      } catch (err) {
        console.error('获取主色调失败:', err);
      }
    };
  }, [imageUrl]);

  return mainColor;
}
